from django.contrib.auth.models import update_last_login, Group
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from rest_framework_simplejwt.settings import api_settings
from rest_framework_simplejwt.serializers import TokenObtainSerializer
from django.contrib.auth import authenticate
from rest_framework_simplejwt.tokens import RefreshToken


class RegisterSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=30, label='账号名', help_text='账号名')
    password = serializers.CharField(min_length=6, label='密码', help_text='密码')

    def validate_password(self, password):
        if len(password) >= 6:
            return password
        raise serializers.ValidationError('密码不能小于6位数,请重新输入！')


class LoginTokenObtainSerializer(TokenObtainSerializer):
    token_class = RefreshToken

    def validate(self, attrs):
        data = {}
        # 对于密码进行解密。再做校验
        attrs['password'] = attrs['password']
        # 校验用户是否存在 (校验用户是否是活跃状态，是否是激活)
        user = authenticate(username=attrs['username'], password=attrs['password'])
        # 生成token
        if user:
            refresh = self.get_token(user)
            data["access"] = str(refresh.access_token)
            data['user'] = user

        if api_settings.UPDATE_LAST_LOGIN:
            update_last_login(None, user)
        return data


class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group
        fields = ['id', 'name']
